﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PanasonicWarranty.Business;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Text;
using Utils;
using Settings;
using System.Dynamic;
using System.Web.Services;

namespace PanasonicWarranty.UI
{
    public partial class SentSMS : BasePageManageSms
    {
        DBWarrantyDataContext DBWarranty = new DBWarrantyDataContext(AppSetting.ConnectionString);
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BindDropDownListData(ddlShorCode, SmsShortCode.GetAll(), "ShortCode", "ShortCode");
                BindDropDownListData(ddlCustomerGroup, pa_CustomerGroup.GetAll(), "CustomerGroupID", "CustomerGroupName", new ListItem(""));
            }
        }

        protected override bool ValidateInfo()
        {
            string err = string.Empty;
            if (string.IsNullOrEmpty(txtMessage.Text.Trim()))
                err = "Tin nhắn không được để trống";
            if (txtMessage.Text.Trim().GetMessageCount() > 3)
                err = "Số bản tin không được phép quá 3 tin nhắn trong một lần gửi";
            if (err != string.Empty)
            {
                ShowMessageBox(err);
                return false;
            }
            return true;
        }

        protected void btnSentMessage_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (ValidateInfo())
                {
                    int totalPhone = 0, invalidPhone = 0;
                    var phoneList = GetPhoneList(txtPhoneList.Text.Trim(), ref totalPhone, ref invalidPhone);
                    if (phoneList.Count == 0)
                    {
                        ShowMessageBox("Chưa có danh sách số điện thoại để gửi tin");
                        return;
                    }
                    //Insert dữ liệu smsMtWaiting
                    SmsMtWaiting.Insert(ddlShorCode.SelectedValue, txtMessage.Text.Trim().ToVietnameseWithoutAccent(), CurUser.AgencyID, phoneList);
                    //Ghi log dữ liệu
                    InsertChangeLog("Gửi tin nhắn. Nội dung: " + txtMessage.Text);

                    txtPhoneList.Text = string.Empty;
                    if (invalidPhone == 0)
                    {
                        ShowMessageBox(string.Format("Gửi thành công {0}/{1} tin nhắn!", totalPhone, totalPhone));
                    }
                    else
                    {
                        ShowMessageBox(string.Format("Gửi thành công {0}/{1} tin nhắn. {2} số điện thoại không hợp lệ!", totalPhone - invalidPhone, totalPhone, invalidPhone));
                    }
                }
            }
            catch(Exception ex)
            {
                HandleException(ex);
            }
        }

        private static List<string> GetPhoneList(string strPhone, ref int totalPhone, ref int invalidPhone)
        {
            List<string> retList = new List<string>();
            var phoneList = strPhone.Split(new string[] { ",", "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
            totalPhone = phoneList.Count;
            invalidPhone = 0;
            foreach (var phone in phoneList)
            {
                var normalPhone = phone.ToNormalPhoneNumber();
                if (OperatorPrefixCode.ValidatePhoneNumber(normalPhone) && !retList.Contains(normalPhone))
                    retList.Add(normalPhone);
                else
                    invalidPhone++;
            }
            return retList;
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                DownloadFile_Tracking(Server.MapPath(string.Format(@"~/App_Data/{0}", AppSetting.PatternFileImportPhoneList)));
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.Message);
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            int? groupCode = ddlCustomerGroup.SelectedValue == "" ? (int?)null : int.Parse(ddlCustomerGroup.SelectedValue);
            List<pa_Customer> list = pa_Customer.GetByCustomerGroup(groupCode);
            string phoneList = "";
            foreach (var item in list)
            {
                phoneList += "," + item.CustomerPhone;
            }
            if (phoneList.Length > 0)
                phoneList = phoneList.Substring(1);
            var text = txtPhoneList.Text.Trim();
            if (text == "")
                txtPhoneList.Text = phoneList;
            else
                txtPhoneList.Text = text + "," + phoneList;
            RegisterStartUpScript("OpenDialog('dialog1',400);");
        }

        [WebMethod]
        public static dynamic CountInvalidPhone(string strPhone)
        {
            int totalPhone = 0, invalidPhone = 0;
            GetPhoneList(strPhone, ref totalPhone, ref invalidPhone);
            return new { TotalPhone = totalPhone, InvalidPhone = invalidPhone };
        }
    }
}